%-------------------------------------------------------------------------
% Subroutine: Figures showing national component per shock
%
% Estimation Codes for State-Level Results in  
% Ben-David, Itzhak, Sebastian Weber, and Pascal Towbin 
% "Inferring Expectations from Observables: Evidence from the Housing Market" 
% Review of Economics and Statistics
% ------------------------------------------------------------------------ 

clear pc1_shock_r2_draw;
pc1=1; % first principal component
strerr=strerr_save;
strerr(:,:,:,37)=[];
n_decomp=n_price_n;

sandstates={'FL';'NV';'AZ';'CA'};
sand_selec=[];
for ss=1: size(sandstates,1)
xx=find(strcmp(state_vec, sandstates{ss}));
sand_selec=[sand_selec xx];
end
no_sand_selec=[];
for ss=1:size(state_vec,1)
    if sand_selec~=ss;
        no_sand_selec=[no_sand_selec ss];
    end
end

   for shock=1:n_var

%       data=diff(squeeze(histirf(n_decomp,:,shock,:)));
%       [weight,pc,~,~,cumR2]=pca_corr(data,'corr');

      for draw=1:size(coll_histirf,4)
              data=diff(squeeze(coll_histirf(n_decomp,:,shock,draw,:)));
              [weight,pc,~,~,cumR2]=pca_corr(data,'corr');
              data_std=(data-kron(ones(size(pc,1),1),mean(data,1)))./std(data);
              pc1_decomp_r2_b_draw(shock,draw)=cumR2(1,1);
              pc1_decomp_r2state_b_draw(shock,draw,:)=1-squeeze(sum((data_std-pc(:,1)*weight(1,:)).^2,1))./sum(data_std.^2,1);
  
              pc1_decomp_r2_b_draw_SaSt(shock,draw)=mean(pc1_decomp_r2state_b_draw(shock,draw,sand_selec),3);
              pc1_decomp_r2_b_draw_NSaSt(shock,draw)=mean(pc1_decomp_r2state_b_draw(shock,draw,no_sand_selec),3)  ;

      end
   end
 


%% Box an Whisker Chart for States
q3=norminv(.75); % Define whisker
q84=norminv(0.84);
w84=(q84-q3)/(2*q3);
xlabel_t={'Expectation shocks','Mortgage rate shocks','Housing consumption shocks','Housing supply shocks'};


% Sand states
coll_speccontrib=flip(mean(pc1_decomp_r2state_b_draw(1:4,:,sand_selec),3))';
 
figure('Name','Figure 7: Sand States Price movement explained by national component')
set(gcf, 'Name','Figure 7: Sand States Price movement explained by national component','NumberTitle','off') 
%boxplot(reshape(coll_speccontrib,[4,size(sand_selec,2)*size(strerr,3)])',xlabel_t,'symbol','','whisker',w84);
boxplot(coll_speccontrib,xlabel_t,'symbol','','whisker',w84);
y1=[0 0.8];
ylim(y1)


% Non-Sand states
coll_speccontrib=flip(mean(pc1_decomp_r2state_b_draw(1:4,:,no_sand_selec),3))';
 
figure('Name','Figure 7: Non-Sand States Price movement explained by national component')
set(gcf, 'Name','Figure 7: Non-Sand States Price movement explained by national component','NumberTitle','off') 
%boxplot(reshape(coll_speccontrib,[4,size(no_sand_selec,2)*size(strerr,3)])',xlabel_t,'symbol','','whisker',w84);
boxplot(coll_speccontrib,xlabel_t,'symbol','','whisker',w84);
y1=[0 0.8];
ylim(y1)

